package cn.lghuntfor.commons.trace.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import cn.lghuntfor.commons.common.result.ReturnData;
import cn.lghuntfor.commons.trace.common.TraceConstant;
import cn.lghuntfor.commons.trace.common.TraceContext;
import cn.lghuntfor.commons.trace.common.TraceInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 链路日志处理过滤器
 * @author liaogang
 * @date 2020/9/10 11:28
 */
@Slf4j
public class TraceGatewayFilter implements GlobalFilter, Ordered {

    @Value("${spring.application.name:}")
    private String springApplicationName;

    @Override
    public int getOrder() {
        /** 用于排序, 值越小越靠前, log优先级最高 */
        return -Integer.MAX_VALUE;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        /** 入口处, 自行创建一个traceId */
        /** 入口处, traceId不存在则自行创建一个 */
        Map<String, String> headerMap = request.getHeaders().toSingleValueMap();
        String tid = headerMap.get(TraceConstant.TID_KEY);
        if (StrUtil.isBlank(tid)) {
            tid = headerMap.get(StrUtil.upperFirst(TraceConstant.TID_KEY));
            if (StrUtil.isBlank(tid)) {
                tid = TraceContext.getTraceId();
            }
        }
        TraceInfo traceInfo = new TraceInfo(tid, springApplicationName);
        TraceContext.addTrace(traceInfo);
        request = request.mutate().header(TraceConstant.TID_KEY, traceInfo.getTid()).header(TraceConstant.PID_KEY, traceInfo.getCid()).build();
        try {
            return chain.filter(exchange.mutate().request(request).build());
        } catch (Exception e) {
            return respMsg(exchange.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR, "服务端异常");
        } finally {
            TraceContext.removeTrace();
        }
    }

    public static Mono<Void> respMsg(ServerHttpResponse resp, HttpStatus httpStatus, String msg) {
        resp.setStatusCode(httpStatus);
        resp.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        ReturnData<String> returnData = new ReturnData<>(httpStatus.value(), msg, null);
        String returnStr = JSON.toJSONString(returnData);
        DataBuffer buffer = resp.bufferFactory().wrap(returnStr.getBytes(StandardCharsets.UTF_8));
        return resp.writeWith(Flux.just(buffer));
    }

}
